<template>
  <div>
    <div class="form-wrapper">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <!-- <el-card title="基本信息" class="form-card"> -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="环境名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入环境名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="环境类型" prop="type">
              <el-select
                v-model="form.type"
                placeholder="请选择环境类型"
                style="width: 100%"
              >
                <el-option label="攻防对抗" value="攻防对抗" />
                <el-option label="单兵作战" value="单兵作战" />
                <el-option label="系统协同" value="系统协同" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="环境描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入环境描述"
          />
        </el-form-item>
        <!-- </el-card> -->

        <!-- <el-card title="网络配置" class="form-card"> -->
        <el-divider />
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="网络段" prop="networkSegment">
              <el-input
                v-model="form.networkSegment"
                placeholder="例如: 192.168.1.0/24"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="网关地址" prop="gateway">
              <el-input
                v-model="form.gateway"
                placeholder="例如: 192.168.1.1"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="DNS服务器" prop="dnsServers">
          <el-input v-model="form.dnsServers" placeholder="多个DNS用逗号分隔" />
        </el-form-item>
        <!-- </el-card>

        <el-card title="主机配置" class="form-card"> -->
        <el-divider />
        <div class="host-config-section">
          <div class="section-header">
            <span>主机列表</span>
            <el-button type="primary" size="small" @click="addHost">
              <el-icon><Plus /></el-icon>
              添加主机
            </el-button>
          </div>

          <div class="host-list">
            <div
              v-for="(host, index) in form.hosts"
              :key="index"
              class="host-item"
            >
              <el-row :gutter="10">
                <el-col :span="6">
                  <el-input v-model="host.name" placeholder="主机名" />
                </el-col>
                <el-col :span="4">
                  <el-input v-model="host.ip" placeholder="IP地址" />
                </el-col>
                <el-col :span="4">
                  <el-select v-model="host.os" placeholder="操作系统">
                    <el-option label="Ubuntu 20.04" value="ubuntu-20.04" />
                    <el-option label="CentOS 8" value="centos-8" />
                    <el-option label="Windows 10" value="windows-10" />
                    <el-option
                      label="Windows Server 2019"
                      value="windows-server-2019"
                    />
                  </el-select>
                </el-col>
                <el-col :span="3">
                  <el-input
                    v-model="host.cpu"
                    placeholder="CPU核数"
                    type="number"
                  />
                </el-col>
                <el-col :span="3">
                  <el-input
                    v-model="host.memory"
                    placeholder="内存(GB)"
                    type="number"
                  />
                </el-col>
                <el-col :span="3">
                  <el-input
                    v-model="host.disk"
                    placeholder="磁盘(GB)"
                    type="number"
                  />
                </el-col>
                <el-col :span="1">
                  <el-button
                    type="danger"
                    
                    plain
                    @click="removeHost(index)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
        <!-- </el-card>

        <el-card title="安全配置" class="form-card"> -->
        <el-divider />
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="启用防火墙">
              <el-switch v-model="form.enableFirewall" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用入侵检测">
              <el-switch v-model="form.enableIDS" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="访问控制规则">
          <el-input
            v-model="form.accessRules"
            type="textarea"
            :rows="4"
            placeholder="请输入访问控制规则，每行一条"
          />
        </el-form-item>
        <!-- </el-card> -->
      </el-form>
    </div>
    <div class="header-actions">
      <el-button @click="goBack">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ isEdit ? "更新" : "创建" }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";

const router = useRouter();
const route = useRoute();
const emit = defineEmits(["cancel"]);
// 响应式数据
const props = defineProps({
  id: {
    type: String,
    default: "",
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
});
const formRef = ref();
const submitting = ref(false);

// 表单数据
const form = reactive({
  name: "",
  type: "",
  description: "",
  networkSegment: "",
  gateway: "",
  dnsServers: "",
  hosts: [],
  enableFirewall: true,
  enableIDS: false,
  accessRules: "",
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入环境名称", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "环境名称长度在 2 到 50 个字符",
      trigger: "blur",
    },
  ],
  type: [{ required: true, message: "请选择环境类型", trigger: "change" }],
  description: [{ required: true, message: "请输入环境描述", trigger: "blur" }],
  networkSegment: [
    { required: true, message: "请输入网络段", trigger: "blur" },
    {
      pattern: /^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/,
      message: "请输入正确的网络段格式",
      trigger: "blur",
    },
  ],
  gateway: [
    { required: true, message: "请输入网关地址", trigger: "blur" },
    {
      pattern: /^(\d{1,3}\.){3}\d{1,3}$/,
      message: "请输入正确的IP地址格式",
      trigger: "blur",
    },
  ],
};

// 生命周期
onMounted(() => {
  if (props.id) {
    loadEnvironmentData(props.id);
  } else {
    // 初始化一个默认主机
    addHost();
  }
});

// 方法
const loadEnvironmentData = async (id) => {
  try {
    // 模拟加载数据
    const mockData = {
      name: "红蓝对抗环境-01",
      type: "攻防对抗",
      description: "模拟企业内网环境，包含多个子网和服务器",
      networkSegment: "192.168.1.0/24",
      gateway: "192.168.1.1",
      dnsServers: "8.8.8.8,8.8.4.4",
      hosts: [
        {
          name: "web-server",
          ip: "192.168.1.10",
          os: "ubuntu-20.04",
          cpu: 2,
          memory: 4,
          disk: 50,
        },
      ],
      enableFirewall: true,
      enableIDS: true,
      accessRules: "allow 22 from 192.168.1.0/24\nallow 80,443 from any",
    };

    Object.assign(form, mockData);
  } catch (error) {
    ElMessage.error("加载环境数据失败");
  }
};

const addHost = () => {
  form.hosts.push({
    name: "",
    ip: "",
    os: "",
    cpu: 2,
    memory: 4,
    disk: 50,
  });
};

const removeHost = (index) => {
  form.hosts.splice(index, 1);
};

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    submitting.value = true;

    // 模拟提交
    await new Promise((resolve) => setTimeout(resolve, 2000));

    ElMessage.success(isEdit.value ? "更新成功" : "创建成功");
    goBack();
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitting.value = false;
  }
};

const goBack = () => {
  emit("cancel");
  // router.push('/tactical-env/list')
};
</script>

<style lang="scss" scoped>
.header-content {
  h2 {
    margin: 0 0 8px 0;
    color: var(--text-color);
    font-size: 24px;
    font-weight: 600;
  }

  p {
    margin: 0;
    color: var(--text-color-secondary);
    font-size: 14px;
  }
}

.form-wrapper {
  padding-top: 20px;
  .form-card {
    margin-bottom: 20px;

    :deep(.el-card__header) {
      background-color: var(--bg-color-secondary);
      font-weight: 600;
    }
  }
}

.host-config-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    span {
      // font-weight: 600;
      // color: var(--text-color);
      display: inline-block;
      width: 108px;
      text-align: right;
    }
  }

  .host-list {
    .host-item {
      margin-bottom: 10px;
      padding: 15px;
      // border: 1px solid var(--border-color);
      border-radius: 6px;
      // background-color: var(--bg-color-secondary);
    }
  }
}
</style>
